const fs = require('fs');
const mongodb = require('mongodb');
const assert = require('assert');
const MongoClient = mongodb.MongoClient;

// 定义数据库连接地址
const url = 'mongodb://localhost:27017';

// 定义需要连接的数据库
const dbName = 'test';

// 创建一个MongoClient
const client = new MongoClient(url, { useUnifiedTopology: true });

// 连接数据库
client.connect(err => {
  assert.ifError(err);
  console.log('Connected successful to server');

  // 切换到test数据库中
  const db = client.db(dbName);
  
  // 在test数据库中创建一个GirdFSBucket
  const bucket = new mongodb.GridFSBucket(db, {
    chunkSizeBytes: 1024 * 1024,
    bucketName: 'my-img'
  });

  // 读取数据库中使用GirdFSBucket存储的数据
  bucket.openDownloadStreamByName('img.jpg').
    pipe(fs.createWriteStream('output.jpg')).
    on('error', error => {
      assert.ifError(error);
    }).
    on('finish', () => {
      console.log('done!');
      process.exit(0);
    });
});